package com.feeyo.groundservice.base.rdb;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import org.influxdb.dto.Point;

import com.feeyo.groundservice.base.util.PropertiesUtils;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.asyncsql.AsyncSQLClient;
import io.vertx.ext.asyncsql.PostgreSQLClient;

public class Postgres2  extends AbstractVerticle{
	   public static AsyncSQLClient postgreSQLClient = null;
	   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    @Override
	    public void start(Future<Void> startFuture) throws Exception {
	        JsonObject postgreSQLClientConfig = new JsonObject().put("host", PropertiesUtils.getProperty("postgresql2.host"))
	                .put("port", Integer.parseInt(PropertiesUtils.getProperty("postgresql2.port")))
	                .put("username", PropertiesUtils.getProperty("postgresql2.user"))
	                .put("password",PropertiesUtils.getProperty("postgresql2.password"))
	                .put("database", PropertiesUtils.getProperty("postgresql2.database"))
	                .put("maxPoolSize", Integer.parseInt(PropertiesUtils.getProperty("postgresql2.maxPoolSize")));
	        postgreSQLClient = PostgreSQLClient.createNonShared(vertx, postgreSQLClientConfig);
	        
	        vertx.eventBus().consumer("tots", msg->{
	            JsonArray ja = (JsonArray)msg.body();
	            String devid = ja.getString(0);
	            //System.out.println("devid:"+devid);
	            
	            Postgres2.postgreSQLClient.getConnection(getConn ->{
                    getConn.result().queryWithParams("insert into public.pos2(time, devid, lat, lon, speed, direct, LOCATION) "
                    		+ " values (?,?,?,?,?,?,?)",
                    	new JsonArray(){{
                        add(sdf.format(new Date()));
                        add(devid);
                        add(ja.getDouble(1));
                        add(ja.getDouble(2));
                        add(ja.getDouble(3));
                        add(ja.getDouble(4));
                        add(true);
                    	}},
                    	r->{
                    		getConn.result().close();
                    });
	            });
	            
	    	    
	        });	        
	        startFuture.complete();
	    }



	    
}
